package org.nf.web.param;

import org.nf.web.annotation.RequestParam;
import org.nf.web.common.TypeConverter;
import org.nf.web.servlet.MethodArgumentsResovler;
import org.nf.web.servlet.ServletApi;

import java.lang.reflect.Parameter;
import java.util.ServiceLoader;

/**
 * @Author lzp
 * @Date 2024-05-17
 * RequsetParam注解参数解析器
 */
public class RequsetParamMethodArgumentResolver implements MethodArgumentsResovler {

    private final ServiceLoader<TypeConverter> LOADER =
            ServiceLoader.load(TypeConverter.class);

    @Override
    public boolean suppots(Parameter parameter) {
        return parameter.isAnnotationPresent(RequestParam.class);
    }

    @Override
    public Object resolve(Parameter parameter, ServletApi servletApi) {
        //获取注解的参数值
        String name = parameter.getAnnotation(RequestParam.class).value();
        //根据参数值从请求对象
        String value = servletApi.request().getParameter(name);
        //针对不同的类型进行转换
        Object obj = null;
        for (TypeConverter converter : LOADER){
            if (converter.supports(parameter.getType())){
                obj = converter.convert(value);
                break;
            }
        }
        if (parameter.getType().isPrimitive() && obj == null){
            throw new RuntimeException("Null value not set" + parameter.getType());
        }
        return obj;
    }

}
